<?php
/**
 *  Yz_Action_Update_Abstract implements the following methods of Yz_Action_Interface as final:
 *  - setModel()
 *  - setItem()
 *  - __invoke(), which is the alias for execute()
 */
class Yz_Action_Update
    extends Yz_Action_Abstract
    implements Yz_Action_Interface
{

    /**
     *  Update requires at least one field/value
     *  @var array
     */
    protected $values = array();


    /************************************
     *          Public methods          *
     ************************************/

    /** @see Yz_Action_Interface::assignFields()
     *  @param hash
     *  @return chainable
     */
    public function assignFields( $fields )
    {
        $fields = new Yz_Hash($fields);
        if (! $fields->isEmpty()) {
            $this->fields = $this->identifyFields($fields);
        }
        return $this;
    }

    /**
     *  @return bool
     */
    public function execute()
    {
        debug();
        if (0 === count($this->values)) {
            // assert that if values are non-empty, the fields have been set, too (@see identifyValues)
            throw new Yz_Exception("Values are required for Update");
        }
        $this->statement = $this
            ->buildUpdate()
            ->execute();
        return $this;
    }

    /** assign values for Update
     *  An Update can not be performed without values
     *  @param hash
     *  @return chainable
     */
    public function assignValues($values)
    {
        $this->values = $this->identifyValues($values);
        return $this;
    }


    /**
     *  Common Update statement creator
     *  @return Yz_SQL_Statement_Update
     */
    protected function buildUpdate()
    {
        debug();
        $tables = $this->tableList;
        $sql = \Yz_SQL_Statement_Update::create()
            ->update($tables->current())
            ->set($this->fields)
            ->bindArray($this->values)
            ;
        /*
        if (count($tables) > 1) {
            $sql->join($tables->slice(1));
        }
        */
        return $sql;
    }


}
